package com.nervenets.web.redis.utils;

import com.nervenets.utils.StringUtils;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisCommands;

/**
 * JEDISCLUSTER生产工厂类
 *
 * @author Administrator
 */
public class JedisFactory implements FactoryBean<JedisCommands>, InitializingBean {
    //REDIS集群地址
    private String host;
    private int port;
    //被注入（生产）的jedisCluster实例
    private JedisCommands jedisCluster;
    //链接超时时间
    private Integer connectionTimeout;

    //操作超时时间
    private Integer timeout;
    //密码（内网集群化不用配置）
    private String password;

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public JedisCommands getObject() throws Exception {
        return jedisCluster;
    }

    @Override
    public Class<? extends JedisCommands> getObjectType() {
        return (this.jedisCluster != null ? this.jedisCluster.getClass() : Jedis.class);
    }

    @Override
    public boolean isSingleton() {
        return true;
    }

    /**
     * 创建JedisCluster实例
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        System.err.println("######jedis初始化######");
        jedisCluster = new Jedis(host, port, timeout);
        if (!StringUtils.isEmpty(password)) {
            ((Jedis) jedisCluster).auth(password);
        }
    }

    public void setTimeout(int timeout) {
        this.timeout = timeout;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public Integer getConnectionTimeout() {
        return connectionTimeout;
    }

    public void setConnectionTimeout(Integer connectionTimeout) {
        this.connectionTimeout = connectionTimeout;
    }
}
